#ifndef SANSERVER_H
#define SANSERVER_H


#include <string>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <QDebug>
#include <QThread>

#define TOTAL_MAX_CLIENTS 5
#define DATA_LEN 100
#define SERVER_QUEUE_SIZE 50000


const int KListenFail   = -1;
const int KBindFail     = -2;
const int KAcceptFail   = -3;
const int KSuccess      = 0;



class SANServer : public QThread
{

    Q_OBJECT
private:
    int iPort;
    int iMaxClients;
    struct sockaddr_in iServAddr;
    int iServSockFd, iBlankSockFd;
    char *iBuf;
    int iLen;
    long long int iCount;
    long long int iDroppedCount;
    FILE *fp;
public:
    QList<QString> iServerQueue;


protected:
    virtual void run(void);

public:
    //ctor
    SANServer();
    //dtor
    ~SANServer();

    void SetServerPort(int aPort);
    void SetMaxClients(int aMaxClients);
    bool SetupConnection();
    int StartServer();
    int AcceptClients();
    void RecvData();
    char *GetBuffer();
    long long int GetCount();
    void ClearSortBuffer();
    long long int GetDroppedCount();
    void DecrementCount();

signals:
    void EmitServerConnected(bool aStatus);
    void EmitClientAccepted(bool aStatus);
    void EmitDataReceived(QString aBuf);
    void EmitSortData();

};

class SANSorting : public QThread
{
    Q_OBJECT
private:
    int iPort;
    std::string iIp;
    struct sockaddr_in iClientAddr;
    int iSockFd;
    char *iBuf;
    long long int iCount;
    SANServer *iServer;

public:
    //ctor
    SANSorting(SANServer *iServer);
    //dtor
    ~SANSorting();

public:
    void SetPort(int aPort);
    void SetIp(std::string aIp);
    int GetPort();
    std::string GetIp();
    bool SetupConnection();
    bool ConnectToClient();
    long long int GetCount();
    void ConnectSortingThread();


protected:
    virtual void run(void);

//public slots:

    //void SortAndSend();

signals:
    void EmitServerToClient(bool aStatus);
    void EmitDisplaySortedData(char *aBuf);
};

#endif // SANSERVER_H
